/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbquestion_client.form;

import bllobjects.Account;
import fsktms.request.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.ClientModel;
import qclient.QClient;
import utils.DefaultPort;

/**
 *
 * @author Mrkupi
 */
public class loginForm extends javax.swing.JFrame {

    /**
     * Creates new form loginForm
     */
    public loginForm() {
        initComponents();
        
        this.setLocation( 400, 200 );
//        SoundRecorder soundRecorder = new SoundRecorder();
//        soundRecorder.getListeners().add(new SoundPlayer());
//        soundRecorder.start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tfID = new javax.swing.JTextField();
        tfPassword = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        btSignIn = new javax.swing.JButton();
        btSignUp = new javax.swing.JButton();
        tfPort = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("LOGIN");
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                onEnter_pressed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("LOGIN");

        tfID.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                onEnter_pressed(evt);
            }
        });

        tfPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                onEnter_pressed(evt);
            }
        });

        jLabel2.setText("ID");

        jLabel3.setText("Password");

        btSignIn.setText("Sign In");
        btSignIn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onSignIn_clicked(evt);
            }
        });
        btSignIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSignInActionPerformed(evt);
            }
        });

        btSignUp.setText("Sign Up");
        btSignUp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onSignUp_clicked(evt);
            }
        });

        jLabel4.setText("Display Name");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(167, 167, 167)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btSignIn)
                        .addGap(18, 18, 18)
                        .addComponent(btSignUp))
                    .addComponent(tfID)
                    .addComponent(tfPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
                    .addComponent(tfPort))
                .addGap(44, 44, 44))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btSignIn)
                    .addComponent(btSignUp))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleName("Login");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void onSignIn_clicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onSignIn_clicked
        
        try
        {
            int port = Integer.parseInt(tfPort.getText());
            DefaultPort.getInstance().setPREPort(port);
        }
        catch (NumberFormatException ex)
        {
            
        }
        
        signInFunc();
    }//GEN-LAST:event_onSignIn_clicked

    private void onSignUp_clicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onSignUp_clicked
        if( makeSureNotEmptyTextField() )
        {
            return;
        }
        // put sign in code here
        final String id   =   this.tfID.getText();
        final String pas  =   String.valueOf( this.tfPassword.getPassword() );
        final String displayName = this.tfPort.getText();
        try 
        {
            RequestParameters params = new RequestParameters()
                                            .set(RequestParameters.KEY_FUNCTION, "register")
                                            .set("ID", id)
                                            .set("Password", pas)
                                            .set("Name", displayName);
            final loginForm copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(
                    new Request("Account", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    Account acc = (Account) respond.get(RequestParameters.KEY_RESULT);
                    if (acc != null)
                    {
                        ClientModel.getInstance().setAccount(acc);
                        ClientModel.getInstance().getForms().getMenu().setVisible(true);
                        copyThis.setVisible(false);
                    }
                    else
                    {
                        // NEED TABLE
                        JOptionPane.showMessageDialog(copyThis, id + " already exist!!");
                    }
                }
            }));
        } catch (IOException ex)
        {
            Logger.getLogger(loginForm.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex);
        }
    }//GEN-LAST:event_onSignUp_clicked

    private void onEnter_pressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_onEnter_pressed
        if( evt.getKeyCode() == KeyEvent.VK_ENTER )
        {
            signInFunc(); 
        }
    }//GEN-LAST:event_onEnter_pressed

    private void btSignInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSignInActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btSignInActionPerformed

    private void signInFunc()
    {
        if( makeSureNotEmptyTextField() )
        {
            return;
        }
        // put sign in code here
        String id   =   this.tfID.getText();
        String pas  =   String.valueOf( this.tfPassword.getPassword() );
        try 
        {
            RequestParameters params = new RequestParameters()
                                            .set(RequestParameters.KEY_FUNCTION, "getAccount")
                                            .set("ID", id)
                                            .set("Password", pas);
            final loginForm copyThis = this;
            QClient.getInstance().getRequestManager().sendRequest(
                    new Request("Account", params, new IRequestDelegate() {

                @Override
                public void requestCompleted(RequestRespond respond) {
                    Account acc = (Account) respond.get(RequestParameters.KEY_RESULT);
                    if (acc != null)
                    {
                        ClientModel.getInstance().setAccount(acc);
                        ClientModel.getInstance().getForms().getMenu().setVisible(true);
                        copyThis.setVisible(false);
                    }
                    else
                    {
                        // NEED TABLE
                        JOptionPane.showMessageDialog(copyThis, "Incorrect account or password");
                    }
                }
            }));
        } catch (IOException ex)
        {
            Logger.getLogger(loginForm.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, ex);
        }
    }
    
    private boolean makeSureNotEmptyTextField()
    {
        //NEED TABLE
        if("".equals( this.tfID.getText() ) )
        {
            JOptionPane.showMessageDialog( this, "You must enter ID" );
            return true;
        }
        
        if( this.tfPassword.getPassword().length <= 0 )
        {
            JOptionPane.showMessageDialog( this, "You must enter password" );
            return true;
        }
        
        return false;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(loginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(loginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(loginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(loginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new loginForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btSignIn;
    private javax.swing.JButton btSignUp;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField tfID;
    private javax.swing.JPasswordField tfPassword;
    private javax.swing.JTextField tfPort;
    // End of variables declaration//GEN-END:variables
}
